<template>
  <!-- 如果iconClass是带协议的图标链接 则通过style属性方式渲染-->
  <div
    class = "svg-icon svg-external-icon"
    v-if = "isExt"
    :style = "styleExternalIcon"
    v-bind = "$attrs"
  ></div>

  <!-- SVG icon 通过名称使用 -->
  <svg v-else :class = "svgClass" aria-hidden = "true" v-bind = "$attrs">
    <!--
       SVG中的use元素可以调用其他SVG文件的元素，<use xlink:href="#symbolId"></use>
    -->
    <use :xlink:href = "iconName"/>
  </svg>
</template>

<script lang = "ts">
import { defineComponent, computed } from 'vue'
import { isExternal } from '@/utils/validate'

export default defineComponent({
  name: 'SvgIcon',
  inheritAttrs: false,
  props: {
    iconClass: { type: String, require: true },
    className: { type: String, default: '' }
  },
  setup(props) {
    /* 是否带有协议的图片链接 */
    const isExt = computed(() => isExternal(props.iconClass || '')),
      iconName = computed(() => `#icon-${ props.iconClass }`),
      svgClass = computed(() => props.className ? `svg-icon ${ props.className }` : 'svg-icon'),
      styleExternalIcon = computed(() => ({
        mask: `url(${ props.iconClass }) no-repeat 50% 50%`,
        '-webkit-mask': `url(${ props.iconClass }) no-repeat 50% 50%`
      }))

    return {
      isExt,
      iconName,
      svgClass,
      styleExternalIcon
    }
  }
})
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>
